<template>
  <div class="shell">
    <div class="upload-shell">
      <h3>上架游戏</h3>
      <div class="container">
        <!-- 上 -->
        <div class="gameInfo">
          <div class="cover-img-container">
            <label>游戏封面</label>
            <div class="cover-img">
              <el-upload class="avatar-uploader" :action="uploadUrl"
                :headers="{ Authorization: 'Bearer ' + token }" :on-success="handleAvatarSuccess"
                :before-upload="beforeImgUpload" :show-file-list="false">
                <img v-if="form.photo" :src="form.photo" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>

              <div class="el-upload__tip">
                请上传最多1张 jpg/png 格式图片
              </div>
            </div>
          </div>
          <ul>
            <li>
              <label>游戏名称</label>
              <el-input v-model="form.gname" placeholder="请输入游戏名称" />
            </li>
            <li>
              <label>游戏定价</label>
              <div class="choose-container">
                <el-input-number v-model="form.price" :min="0" :max="9999" :step="1" :precision="2" />
                <span>元</span>
              </div>
            </li>
            <li>
              <label>游戏类别</label>
              <el-select v-model="form.tname" placeholder="请选择游戏类别" clearable>
                <el-option label="动作" value="动作" />
                <el-option label="冒险" value="冒险" />
                <el-option label="休闲" value="休闲" />
                <el-option label="模拟" value="模拟" />
                <el-option label="竞速" value="竞速" />
                <el-option label="恐怖" value="恐怖" />
                <el-option label="角色扮演" value="角色扮演" />
                <el-option label="生存" value="生存" />
                <el-option label="策略" value="策略" />
              </el-select>
            </li>
            <li>
              <label>开发者信息</label>
              <el-input v-model="form.company" placeholder="请输入开发者信息" />
            </li>
            <li class="bigli">
              <label>游戏标签</label>
              <div class="flex gap-2">
                <el-tag class='tag' v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false"
                  @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" size="small" class='tag'
                  @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                <el-button v-else class='tag' size="small" type="primary" @click="showInput">
                  + 添加标签
                </el-button>
              </div>
            </li>
            <li class="bigli">
              <label>游戏文件</label>
              <div>
                <el-upload :action="uploadUrl" :limit=1
                  :headers="{ Authorization: 'Bearer ' + token }" :on-success="handleFileSuccess"
                  :before-upload="beforeZipUpload" :on-exceed="handleExceed">
                  <el-button type="primary">点击上传</el-button>
                  <div class="el-upload__tip">
                    请上传 zip 格式的文件，最多一个
                  </div>
                </el-upload>
              </div>
            </li>
          </ul>
        </div>
        <!-- 游戏描述 -->
        <div class="desc">
          <label>游戏描述</label>
          <el-input v-model="form.detail" type="textarea" placeholder="请输入游戏描述" />
        </div>
        <!-- 图片 -->
        <div class="img-container">
          <div class="imgs">

            <div class="icon-container">
              <label>游戏图标</label>
              <div class="imgupload-div">
                <el-upload class="icon-uploader" :action="uploadUrl" :show-file-list="false"
                  :headers="{ Authorization: 'Bearer ' + token }" :on-success="handleIconSuccess"
                  :before-upload="beforeImgUpload">
                  <img v-if="form.icon" :src="form.icon" class="icon" />
                  <el-icon v-else class="icon-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
                <div class="el-upload__tip">
                  请上传最多1张 jpg/png 格式图片
                </div>
              </div>
            </div>
            <!-- 游戏描述图 -->
            <div class="imgs-container">
              <label style="margin-bottom: 10px;">游戏描述图</label>
              <div class="upload-container">
                <el-upload class="desc-images-uploader" :action="uploadUrl" :show-file-list="true"
                  :headers="{ Authorization: 'Bearer ' + token }" :on-success="handleDescImagesSuccess"
                  :before-upload="beforeImgUpload" multiple :limit="4" :file-list="fileList"
                  list-type="picture-card" :on-exceed="handleDescImagesExceed"
                  :on-remove="handleDescImagesRemove" :preview-src-list="gameDescImages.filter(url => url)"
                  :on-preview="handlePictureCardPreview">
                  <el-icon class="icon-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
                <div class="el-upload__tip">
                  请上传最多4张 jpg/png 格式图片
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="btn">
          <el-button type="primary" @click="submitForm">提交上传</el-button>
        </div>
      </div>
      <el-dialog v-model="dialogVisible" class="preview-dialog">
        <img w-full :src="dialogImageUrl" class="preview-image" alt="Preview Image" />
      </el-dialog>
      <div style="height: 100px"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, computed } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import GameInfoCard from '@/components/gameInfoCard.vue';
import { myAxios } from '@/axios/index';
import { useStore } from 'vuex'; // 导入 useStore

const token = localStorage.getItem('token');
const store = useStore(); // 使用 store

// 创建计算属性获取 baseURL
const baseURL = computed(() => store.state.baseUrl);
// 创建上传地址计算属性
const uploadUrl = computed(() => `${baseURL.value}/upload`);

// 表单数据
const form = reactive({
  gname: '',
  price: 0,
  tname: '',
  moretype: '',
  detail: '',
  company: '',
  path: null,
  photo: '',
  icon: '',
  photoa: '',
  photob: '',
  photoc: '',
  photod: ''
});

const dialogVisible = ref(false);
const dialogImageUrl = ref('');

// 存储动态标签的数组
const dynamicTags = ref([]);
// 控制输入框是否显示
const inputVisible = ref(false);
// 输入框的值
const inputValue = ref('');
// 输入框的引用
const InputRef = ref(null);
// 上传的文件列表（用于描述图）
const fileList = ref([]);
// 选中的文件名（用于游戏文件上传）
const selectedFileName = ref('');
// 游戏描述图预览数组
const gameDescImages = computed(() => {
  return [
    form.photoa || '',
    form.photob || '',
    form.photoc || '',
    form.photod || ''
  ];
});

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 图片上传前检验格式大小
const beforeImgUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 <= 2;
  if (!isImage) {
    // console.error('仅支持图片文件上传');
    ElMessage.error('仅支持上传jpg,png等的图片格式');
    return false;
  }
  if (!isLt2M) {
    // console.error('文件大小不能超过2MB');
    ElMessage.error('图片大小不能超过2MB');
    return false;
  }
  return true;
};
// 封面图片上传成功
const handleAvatarSuccess = (response, file, fileList, index) => {
  if (response.code === 200) {
    form.photo = response.data;
    console.log('图标上传成功', response, file, fileList);
  } else {
    if (response.status === 401) {
      ElMessage.error('身份验证失败，请重新登录');
    } else {
      ElMessage.error('图片上传失败');
    }
    console.log(response.data);
  }
};
// 图标图片上传成功
const handleIconSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    form.icon = response.data;
    console.log('封面图片上传成功', response, file, fileList);
  } else {
    if (response.status === 401) {
      ElMessage.error('身份验证失败，请重新登录');
    } else {
      ElMessage.error('图片上传失败');
    }
    console.log(response.data);
  }
};

// 描述图上传成功处理函数
const handleDescImagesSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    // 根据当前上传的图片数量，将URL分配到对应的form属性
    const imageIndex = fileList.findIndex(item => item.uid === file.uid);
    if (imageIndex === 0) {
      form.photoa = response.data;
    } else if (imageIndex === 1) {
      form.photob = response.data;
    } else if (imageIndex === 2) {
      form.photoc = response.data;
    } else if (imageIndex === 3) {
      form.photod = response.data;
    }
    console.log('描述图上传成功', response, file, fileList);
  } else {
    if (response.status === 401) {
      ElMessage.error('身份验证失败，请重新登录');
    } else {
      ElMessage.error('图片上传失败');
    }
  }
};

// 处理描述图超出限制
const handleDescImagesExceed = (files) => {
  ElMessage.warning('最多只能上传4张描述图');
};

// 处理描述图移除
const handleDescImagesRemove = (file, fileList) => {
  // 找到被移除图片的索引
  const removedIndex = gameDescImages.value.findIndex(url => url === file.url);
  if (removedIndex === 0) {
    form.photoa = '';
  } else if (removedIndex === 1) {
    form.photob = '';
  } else if (removedIndex === 2) {
    form.photoc = '';
  } else if (removedIndex === 3) {
    form.photod = '';
  }
};

// 文件上传前检验格式大小
const beforeZipUpload = (file) => {
  const isZip = file.name.slice(-4).toLowerCase() === '.zip';
  const isLt10M = file.size / 1024 / 1024 <= 10;
  if (!isZip) {
    ElMessage.error('仅支持上传 zip 格式的文件');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB');
    return false;
  }
  return true;
};

const handleFileSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    form.path = response.data;
    console.log('游戏文件上传成功', response, file, fileList);
  } else {
    if (response.status === 401) {
      ElMessage.error('身份验证失败，请重新登录');
    } else {
      ElMessage.error('游戏文件上传失败');
    }
    console.log(response.data);
  }
};
const handleExceed=(files)=>{
  ElMessage.warning('最多只能上传一个游戏文件,如需更换游戏文件，请先删除游戏文件');
}

// 添加游戏标签的方法
const showInput = () => {
  if (dynamicTags.value.length >= 5) {
    ElMessage.warning('最多添加 5 个标签');
    return;
  }
  inputVisible.value = true;
  nextTick(() => {
    if (InputRef.value) {
      InputRef.value.focus();
    }
  });
};
//标签数量控制
const handleInputConfirm = () => {
  if (inputValue.value.length > 4) {
    ElMessage.warning('每个标签不能超过四个字符');
    inputValue.value = '';
    inputVisible.value = false;
    return;
  }
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value);
    form.moretype = dynamicTags.value.join(',');
  }
  inputVisible.value = false;
  inputValue.value = '';
};
// 关闭标签的方法
const handleClose = (tag) => {
  const index = dynamicTags.value.indexOf(tag);
  if (index > -1) {
    dynamicTags.value.splice(index, 1);
    form.moretype = dynamicTags.value.join(',');
  }
};

const isVadild = () => {
  if (!form.gname.trim()) {
    ElMessage.error('请填写游戏名称');
    return;
  }
  if (form.price <= 0) {
    ElMessage.error('请填写有效的游戏定价');
    return;
  }
  if (!form.tname) {
    ElMessage.error('请选择游戏类型');
    return;
  }
  if (!form.moretype) {
    ElMessage.error('请填写至少一个游戏标签');
    return;
  }
  if (!form.detail.trim()) {
    ElMessage.error('请填写游戏简介');
    return;
  }
  if (!form.company.trim()) {
    ElMessage.error('请填写开发者信息');
    return;
  }
  if (!form.path) {
    ElMessage.error('请上传游戏文件');
    return;
  }
  if (!form.photo) {
    ElMessage.error('请上传游戏封面图片');
    return;
  }
  if (!form.icon) {
    ElMessage.error('请上传游戏图标图片');
    return;
  }
  if (!form.photoa) {
    ElMessage.error('请上传第一张游戏描述图');
    return;
  }
  if (!form.photob) {
    ElMessage.error('请上传第二张游戏描述图');
    return;
  }
  if (!form.photoc) {
    ElMessage.error('请上传第三张游戏描述图');
    return;
  }
  if (!form.photod) {
    ElMessage.error('请上传第四张游戏描述图');
    return;
  }
};
// 提交表单的方法
const submitForm = async () => {
  const confirmResult = await ElMessageBox.confirm('确认要上传游戏吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).catch(() => {});

  if (confirmResult === 'cancel') {
    return;
  }
  isVadild();
  try {
    console.log('提交表单', form);
    ElMessage('正在上传...');
    const res = await myAxios.post('/goodsAdmin/uploadGame', form);
    ElMessage.closeAll();
    ElMessage.success('上传成功');
    console.log('提交:', res);
    
  } catch (error) {
    console.error('提交失败:', error);
  }
};

</script>

<style lang="less" scoped>
.shell {
  height: calc(100vh - 72px);
  width: 100%;

  .upload-shell {
    max-width: 960px;
    margin: 0px auto;
    height: 100%;
    // background-color: #172636;
    padding: 10px;
    box-sizing: border-box;

    h3 {
      padding: 20px;
      padding-left: 25px;
      color: rgb(26, 159, 255) !important;
    }

    label {
      color: #9fa9b5;
      margin-bottom: 5px;
    }

    .container {
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin: 0 auto;
      padding-left: 100px;
      margin-bottom: 20px;

      .gameInfo {
        display: flex;
        flex-direction: row;
        height: 210px;

        .cover-img-container {
          width: 200px;
          height: 200px;
          margin-right: 50px;

          .cover-img {
            width: 175px;
            height: 175px;
            background-color: white;
            border-radius: 5px;
            margin-top: 5px;


            .avatar-uploader {
              width: 175px;
              height: 175px;
              display: block;
            }

            .avatar-uploader .el-upload {
              border: 1px dashed var(--el-border-color);
              border-radius: 6px;
              cursor: pointer;
              position: relative;
              overflow: hidden;
              transition: var(--el-transition-duration-fast);
            }

            .avatar-uploader .el-upload:hover {
              border-color: var(--el-color-primary);
            }

            .el-icon.avatar-uploader-icon {
              font-size: 28px;
              color: #8c939d;
              width: 175px;
              height: 175px;
              text-align: center;
            }

            .avatar {
              width: 175px;
              height: 175px;

              text-align: center;
              object-fit: contain;
            }
          }
        }

        ul {
          list-style: none;
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          grid-gap: 15px;
          width: 60%;
          height: 200px;

          li {
            display: flex;
            flex-direction: column;
            width: 180px;
            height: 60px;
            justify-content: space-between;
          }

          .choose-container {
            display: flex;

            .el-button {
              border-top-left-radius: 0;
              border-bottom-left-radius: 0;
              border-top-right-radius: 5px;
              border-bottom-right-radius: 5px;
            }

            span {
              width: 30px;
              text-align: center;
              line-height: 30px;
              color: white;
            }
          }

          .bigli {
            width: 250px;
            height: 100px;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;

            .tag {
              width: 70px;
              height: 30px;
              margin-top: 5px;
              margin-right: 5px;
              margin-left: 0px;
              margin-bottom: 0px;
            }

            .el-upload__tip {
              margin-left: 5px;
              color: #7f868f;
              font-size: 10px
            }

            .el-upload-list__item-name {
              background-color: white;
            }

            :deep(.el-upload-list__item) {
              background-color:rgb(197.7, 225.9, 255);
              color: #333;
              width: 150px;
              line-height: 20px;

              &:hover {
                background-color:rgb(216.8, 235.6, 255);
                width: 200px;
              }

              .el-upload-list__item-delete {
                color: #ff0000;

                &:hover {
                  color: #cc0000;
              
                }
              }
            }
          }
        }
      }

      .desc {
        margin-top: 30px;
        width: 80%;

        &::v-deep .el-textarea__inner {
          margin-top: 10px;
          width: 620px;
          height: 100px;
        }
      }

      .img-container {
        margin-top: 10px;
        height: 160px;

        display: flex;
        justify-content: space-between;
        flex-direction: row;

        .imgs {
          display: flex;
          flex-direction: row;
          height: 100%;

          .la {
            margin-top: 5px;
          }

          .icon-container {
            width: 120px;
            margin-right: 20px;
          }

          .imgs-container {
            width: 600px;

            :deep(.el-upload--picture-card) {
              width: 110px;
              height: 110px;
            }

            :deep(.el-upload-list--picture-card .el-upload-list__item) {
              width: 110px;
              height: 110px;
            }
          }

          .imgupload-div {
            background-color: white;
            border-radius: 5px;
            width: 110px;
            height: 110px;
            margin-top: 5px;


            .icon-uploader {
              width: 110px;
              height: 110px;
              display: block;
            }

            .icon-uploader .el-upload {
              border: 1px dashed var(--el-border-color);
              border-radius: 6px;
              cursor: pointer;
              position: relative;
              overflow: hidden;
              transition: var(--el-transition-duration-fast);
            }

            .icon-uploader .el-upload:hover {
              border-color: var(--el-color-primary);
            }

            .el-icon.icon-uploader-icon {
              font-size: 28px;
              color: #8c939d;
              width: 110px;
              height: 110px;
              text-align: center;
            }

            .icon {
              width: 110px;
              height: 110px;
              text-align: center;
              object-fit: contain;
            }
          }

          .upload-container {
            width: 100%;
            height: auto;
            margin-top: 6px;
            background-color: #1A2A3C;
          }
        }
      }

      .btn {
        display: flex;
        justify-content: flex-end;
        padding-right: 100px;

        .el-button {
          width: 100px;
        }
      }
    }
  }
}
// 添加预览图片的样式
.preview-dialog {
    :deep(.el-dialog__body) {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10px;
        min-height: 300px;
        box-sizing: border-box;
    }
    
    :deep(.el-dialog__header) {
        margin-right: 0;
        text-align: center;
    }
    
    :deep(.el-dialog) {
        display: flex;
        flex-direction: column;
    }
}

.preview-image {
    max-width: 100%;
    max-height: 64vh; // 设置最大高度为视口高度的70%
    object-fit: contain;
    margin: 0 auto;
    display: block;
}
</style>